package com.coke.spring.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author cwm
 * @Description 自定义请求响应时间统计过滤器工厂
 * @date 2021/9/7 下午4:00
 * @Version 1.0
 */
@Slf4j
@Component
public class TimeMonitorGatewayFilterFactory extends AbstractGatewayFilterFactory<TimeMonitorGatewayFilterFactory.Config> {

    private static final String COUNT_START_TIME = "countStartTime";

    public TimeMonitorGatewayFilterFactory() {
        super(TimeMonitorGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new TimeMoniterFilter(config);
    }

    /**
     *  重写GatewayFilter实现优先级
     */
    static class TimeMoniterFilter implements GatewayFilter, Ordered{
        private final TimeMonitorGatewayFilterFactory.Config config;

        public TimeMoniterFilter(TimeMonitorGatewayFilterFactory.Config config) {
            this.config = config;
        }

        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            boolean enabled = config.isEnabled();
            log.info("enabled:{}",enabled);
            if (!enabled){
                return chain.filter(exchange);
            }
            exchange.getAttributes().put(COUNT_START_TIME, System.currentTimeMillis());

            //then方法相当于aop的后置通知一样
            return chain.filter(exchange).then(Mono.fromRunnable(()->{
                Long startTime = exchange.getAttribute(COUNT_START_TIME);
                if (startTime != null) {
                    StringBuilder sb = new StringBuilder(exchange.getRequest().getURI().getRawPath())
                            .append(": ")
                            .append(System.currentTimeMillis() - startTime)
                            .append("ms");
                    sb.append(" params:").append(exchange.getRequest().getQueryParams());
                    log.info(sb.toString());
                }
            }));
        }

        @Override
        public int getOrder() {
            //值越小优先级越高
            return -100;
        }
    }

    public static class Config {
        // 控制是否开启认证
        private boolean enabled;

        public Config() {}

        public boolean isEnabled() {
            return enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
    }

}
